import sys, json, re, os

author_info = "\\author{  猫姐 \\\\ 211硕-养花种树  \\and 猫哥 \\\\ 985博-厂里搬砖}\n"
insti_info = "\\institute{\\href{https://gitee.com/yeta}{@喵星趣学堂}}"

def create_exam(tex_file):
    fd = open(tex_file, "r", encoding="utf-8")
    # print (fd.readlines())
    p1 = re.compile(r'{.*?}', re.S) 
    p2 = re.compile(r'{.*?}', re.S) 
    lines = fd.readlines()
    title = lines[0]
    record_date = lines[1]
    # print (title, record_date)    
    title  = re.findall(p1, title)[0][1:-1]
    record_date = "\\date{}"
    content_body = lines[1:]
    # print (title, record_date)
    return title , record_date , content_body





def read_template(template_file):
    fd = open(template_file, "r", encoding="utf-8")
    # content = fd.read()
    # print (content)
    stage = "stop"
    header = []
    body = []
    for line in fd:
        # print(line)
        if stage == "stop":  
            line = line.strip()
            if line == "header":
                stage = "header"
                continue
        elif stage == "header":
            line = line.strip()
            if line == "body":
                stage = "body"
                continue
            if len(line):
                # print ("header:", line)
                header.append(line)
        elif stage == "body":
            line = line.strip()
            if len(line):
                # print("body:", line)
                body.append(line)            
        else:
            print("wrong")
    fd.close()
    # print(header)
    # print(body)
    return header, body

def write_template_header(fd, header_list):
    for h in header_list:
        fd.write(h + "\n")

def write_template_body(fd, body_list):
    for h in body_list:
        fd.write(h + "\n")

def remove_tmp_files():
    os.system ("rm -rf ./output/*.aux")    
    os.system ("rm -rf ./output/*.log")    
    os.system ("rm -rf ./output/*.out")    
    os.system ("rm -rf ./output/*.xml")    
    os.system ("rm -rf ./output/*.bib")    
def latex_to_pdf(tex_filename):
    """
    在output目录，将tex文件转化为pdf文件
    """
    cmd = "xelatex  -output-directory ./output " + tex_filename
    print(cmd)
    # 下面命令必须运行两遍
    os.system (cmd)
    os.system (cmd)
    remove_tmp_files()

def append_tex_files_to_list(file_path):
    all_content = []
    fd = open(file_path + "/chapter.tex", "r", encoding="utf-8")
    chapter_content = fd.readlines()
    chapter_content = chapter_content[1:]
    all_content.extend(chapter_content)
    section_tex_files = []

    # 得到section所有文件名，并排序，得到section1.tex, section2.tex ...
    for tex_file in os.listdir(file_path):
        if "section" in tex_file:
            section_tex_files.append(tex_file)
    # print(section_tex_files)            
    section_tex_files.sort()
    # print(section_tex_files)
    base_path = file_path + "/"
    for tex_file in section_tex_files:
        # print(tex_file)
        fd =open(base_path + tex_file, "r", encoding="utf-8")
        content = fd.readlines()
        all_content.extend(content)    
    return all_content

def get_title_from_chapter(chapt_file):
    fd  = open(chapt_file, "r", encoding="utf-8")
    title = ""
    for line in fd.readlines():
        if "chapter" in line:
            title = line
            break
    title = title.replace("chapter", "title")
    return title

def create_chapter(chapter_num, is_debug):
        output_tex = "./output/chapter" + chapter_num  + ".tex"

        section_template = "../template/game_section.json"
        template_header, template_body = read_template(section_template)
        fd = open(output_tex, "w", encoding="utf-8")
        write_template_header(fd, template_header)
        title = get_title_from_chapter("./book/chapter" + chapter_num + "/chapter.tex")
        fd.write(title)
        fd.write(author_info)    
        fd.write(insti_info)
        write_template_body(fd, template_body)

        # 得到所有的section[x].tex, 追加至output_tex文件
        content_body = append_tex_files_to_list("./book/chapter" + chapter_num)

        write_template_body(fd, content_body)
        fd.write("\\end{document}")
        fd.close()
        if is_debug == "-r":
            latex_to_pdf(output_tex)
        else:
            print("[deub mode]: just generated tex file")
           
            


if __name__ == "__main__":
    if len(sys.argv) == 4:
        chapter_num = sys.argv[1]
        section_num = sys.argv[2]
        output_tex = "./output/chapter" + chapter_num + "_" + section_num + ".tex"
        input_tex_file = "./book/chapter" + str(chapter_num) + "/section" + str(section_num) +".tex"
        print("#####", input_tex_file)
        title, record_date, content_body = create_exam(input_tex_file)
        section_template = "../template/game_section.json"
        header, body = read_template(section_template)
        fd = open(output_tex, "w", encoding="utf-8")
        write_template_header(fd, header)
        title = "\\title{" + title + "}\n"
        fd.write(title)
        fd.write(author_info)    
        fd.write(insti_info)
    
        write_template_body(fd, body)
        write_template_body(fd, content_body)
        fd.write("\\end{document}")
        fd.close()

        latex_to_pdf(output_tex)

        # 加上头latex模板信息
        # 输出latex
        # 调用xelate生成pdf

    elif len(sys.argv) == 3:
        chapter_num = str(sys.argv[1])
        is_debug = str(sys.argv[2])
        print("Generating a single chapter:" + chapter_num)
        create_chapter(chapter_num, is_debug)

    else:
        print("Generating a complete book")
        # create_book()

        # python get_math.py  1 1 && xelatex exam.tex